<template>
  <div class="box">
    <el-card>
      <!-- 卡片头部区域 -->
      <template #header>
        <div class="card-header">
          <img src="../../images/login-head.png" alt="" />
        </div>
      </template>
      <div class="optionState">
        <el-link type="primary" @click="handleChange">
          {{ logInState ? '注册账号' : '返回登录' }}
        </el-link>
      </div>
      <!-- 表单区域 -->
      <el-form
        :model="formObj"
        label-width="auto"
        :rules="rules"
        ref="loginFormRef"
      >
        <el-form-item prop="userName">
          <el-input placeholder="手机号" v-model.trim="formObj.userName" />
        </el-form-item>
        <el-form-item prop="passWord">
          <el-input placeholder="密码" v-model.trim="formObj.passWord" />
        </el-form-item>
        <!-- 只有是注册账号的时候显示 -->
        <el-form-item v-show="!logInState" prop="validCode">
          <el-input placeholder="验证码" v-model="formObj.validCode">
            <template #append>
              <div @click="gainCode" class="code-box">
                {{ time != 60 ? time : '获取验证码' }}
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            class="btn-box"
            @click="submitForm(loginFormRef)"
          >
            {{ logInState ? '登录' : '注册账号' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { phoneRule, passwordRule } from '@/utils/rule.js'
import { getCodeApi, registerApi, loginApi } from '@/api/loginAPi.js'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const logInState = ref(true) // 记录当前的登录状态
const time = ref(60)
const timeState = ref(true)
const loginFormRef = ref()
const store = useStore()
const router = useRouter()
const formObj = reactive({
  userName: '', // 手机号
  passWord: '', // 密码
  validCode: '', // 验证码
})
// 自定义手机号验证
const validateName = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else {
    if (!phoneRule(value)) {
      callback(new Error('请输入正确手机号'))
    } else {
      callback()
    }
  }
}
// 自定义密码验证
const validatePassWord = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (!passwordRule(value)) {
      callback(new Error('密码需要4到16位字符'))
    } else {
      callback()
    }
  }
}
const rules = reactive({
  userName: [{ validator: validateName, trigger: 'blur' }],
  passWord: [{ validator: validatePassWord, trigger: 'blur' }],
})

// 点击切换当前是否为登录或者注册的状态
const handleChange = () => {
  logInState.value = !logInState.value
}
// 获取验证码接口
const getCode = async () => {
  await getCodeApi({
    tel: formObj.userName,
  })
}
// 点击获取验证码
const gainCode = () => {
  // 先单独验证手机号是否正确
  loginFormRef.value.validateField('userName', (valid) => {
    if (!valid) return
    if (!timeState.value) return
    timeState.value = false
    getCode()
    const timer = setInterval(() => {
      if (time.value <= 0) {
        time.value = 60
        clearInterval(timer)
        timeState.value = true
      } else {
        time.value = time.value - 1
      }
    }, 1000)
  })
}
// 注册账号方法
const register = async () => {
  const res = await registerApi(formObj)
  if (res.code === 10000) {
    ElMessage({
      message: '注册成功,请登录',
      type: 'success',
    })
    logInState.value = true
  }
}
// 登录账号方法
const login = async () => {
  const res = await loginApi({
    userName: formObj.userName, // 手机号
    passWord: formObj.passWord, // 密码
  })
  if (res.code === 10000) {
    ElMessage({
      message: '登录成功',
      type: 'success',
    })
    store.commit('recordToken', res.data.token)
    store.commit('recordUser', JSON.stringify(res.data.userInfo))
    logInState.value = true
    router.push('/')
  }
}
// 点击登录或者注册
const submitForm = (value) => {
  if (!value) return
  value.validate((valid) => {
    if (valid) {
      logInState.value ? login() : register()
    } else {
      console.log('error submit!')
    }
  })
}
</script>

<style scoped lang="less">
.box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  /deep/ .el-card__header {
    padding: 0;
  }
  .card-header {
    background: #899fe1;
    img {
      width: 430px;
    }
  }
  .optionState {
    display: flex;
    justify-content: end;
    margin-bottom: 10px;
  }
  .btn-box {
    width: 100%;
  }
  .code-box:hover {
    cursor: pointer;
  }
}
</style>
